//
//  LAMerchantDetailVideoTableView.m
//  LYLazizDevelopDemo
//
//  Created by xbn_iMac on 2016/10/25.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LAMerchantDetailVideoTableView.h"
#import "LZVideoTableViewCell.h"
#import "LZCustomPlayerView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UITableView+LZTableView.h"
#import "LZPlayVideoManager.h"
#import "XBNTimeLimitCountDownCalculator.h"
#import "Masonry.h"

@interface LAMerchantDetailVideoTableView ()<UITableViewDelegate,UITableViewDataSource,LZ_MainTableViewCellDelegate,LZPlayVideoManagerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) LZCustomPlayerView *playerView;
@property (nonatomic, strong) NSIndexPath *currentPlayCellIndexPath;

@property (nonatomic, assign) int page;
@property (nonatomic, assign) int limit;

@property (nonatomic, assign) NSTimeInterval request_timeStemp;

@property (nonatomic, assign) NSTimeInterval timeStamp;
@property (strong, nonatomic) XBNTimeLimitCountDownCalculator *timeCountDownCalculator;

@end

@implementation LAMerchantDetailVideoTableView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.separatorColor = [UIColor clearColor];
        self.backgroundColor = UIColorFromRGB(0xeeeeee, 1);

        [LZPlayVideoManager shareManager].playVideoManagerDelegate = self;
        [self registerCell];
        self.delegate = self;
        self.dataSource = self;
        [self configBaseData];
    }
    return self;
}

#pragma mark - Public Method

- (void)stopPlayVideo {
//    [self.playerView stopAction];
    [[LZPlayVideoManager shareManager] stopPlayWithPlayerView:self.playerView];

}

- (void)startPlayVideo {
//    [self.playerView playAction];
  self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] goOnPlayWithCellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView tableView:self playCountAddBlock:^(NSInteger totleCount) {
      
    }];
}

- (void)checkHaveData {
    if (self.dataArr.count == 0) {
        if (self.subTableDelegate && [self.subTableDelegate respondsToSelector:@selector(requestDateWithType:andPrameter:andPage:andLimit:resultSuccess:)]) {
            if (self.mj_footer.state != MJRefreshStateRefreshing) {
                [self.mj_footer beginRefreshing];
            }
        }
    }
}

/* --------------------- configure Super Refresh method --------------------- */

- (void)upLoadMoreData {
    [self requestList];
}

- (void)requestList {
    
    WS(weakSelf)
    [self.subTableDelegate requestDateWithType:TableViewType_Video andPrameter:@{@"timestamp":[NSNumber numberWithLong:self.request_timeStemp]} andPage:self.page andLimit:self.limit resultSuccess:^(NSArray *result,NSNumber *timeStemp) {
        
        [weakSelf.mj_footer endRefreshing];

        if (result) {
            if (weakSelf.timeStamp == 0) {
                weakSelf.timeStamp = [timeStemp longLongValue]/1000;
            }
            weakSelf.page ++;
            
            if (weakSelf.request_timeStemp == 0) {
                weakSelf.request_timeStemp = [timeStemp longLongValue];
            }

            if (result.count>0) {
                [weakSelf.dataArr addObjectsFromArray:result];
                [weakSelf reloadData];
            }
            else {
                if (weakSelf.dataArr.count == 0) {
                    [weakSelf setNoDataFooterText];
                }
                else {
                    [weakSelf setNoMoreDataFooterText];
                }
                [weakSelf.mj_footer endRefreshingWithNoMoreData];
            }
        }
    }];
}

#pragma mark - Private Method

- (void)registerCell
{
    [self registerClass:[LZVideoTableViewCell class] forCellReuseIdentifier:@"videocell"];
}

- (void)configBaseData {
    self.page = 1;
    self.limit = 10;
    self.timeStamp = 0;
    self.request_timeStemp = 0;
    self.dataArr = [NSMutableArray array];
}

#pragma mark -
#pragma mark currentTimer 倒计时相关
- (void)setTimeStamp:(NSTimeInterval)timeStamp
{
    if (timeStamp == 0) {
        return;
    }
    _timeStamp = timeStamp;
    // 开起计时器
    [self startTimeCountDown];
}

- (void)startTimeCountDown {
    if (self.timeCountDownCalculator) {
        return;
    }
    // ******************** 创建计时器 ********************
    self.timeCountDownCalculator = [XBNTimeLimitCountDownCalculator new];
    
    // 取出服务器时间
    self.timeCountDownCalculator.remainTimeInterval = self.timeStamp;
    
    // 以服务器时间为标准时间开始计算
    WS(weakSelf);
    [self.timeCountDownCalculator addProcessBlock:^(NSTimeInterval remain) {
        weakSelf.timeStamp += 1;
    } cancelBlock:^{
        DLog(@"结束了");
    }];
    
    [self.timeCountDownCalculator timeLimitCountDownResume];
    
}

#pragma mark -
#pragma mark tableview delegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(wSelf);
    return [tableView fd_heightForCellWithIdentifier:@"videocell" configuration:^(id cell) {
        LZVideoTableViewCell *cellTemp = (LZVideoTableViewCell *)cell;
        LZVideoListModel *m = wSelf.dataArr[indexPath.row];
        [cellTemp loadDataWithIndex:indexPath WithShowHeadView:NO showCellBtns:YES showCouponAndGroupsView:YES];
        cellTemp.model = m;
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"videocell"];
    if (cell == nil) {
        cell = [[LZVideoTableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"videocell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainDelegate = self;
    cell.cellClickDelegate = self.videoDelegate;
    
    [cell loadDataWithIndex:indexPath WithShowHeadView:NO showCellBtns:YES showCouponAndGroupsView:YES];
    LZVideoListModel *model = _dataArr[indexPath.row];
    model.currentTime = self.timeStamp;
    cell.model = model;
    [cell startTimeDown];
    
    return cell;
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!decelerate){//缓慢拖动.手指离开时
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
            
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
        
    }];
    
}

- (void)lzScrollViewDidScroll:(UIScrollView *)scrollView {
    //滑动时判断当前播放的cell是否已经离开屏幕.已经离开,停止播放
    [[LZPlayVideoManager shareManager] removePlayViewWhenTableViewDidScrollWithTableView:self cellIndexPath:_currentPlayCellIndexPath];
}

/**
 点击视频海报播放协议
 */
- (void)playVideoWhenClickVideoCoverImgWithIndex:(NSIndexPath *)cellIndexPath
{
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenClickVideoCoverImgWithIndexPath:cellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
        
    }];
    [self scrollToRowAtIndexPath:cellIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark -
#pragma mark  播放控制器获取资源delegate
- (NSString *)playVideoManagerGetVideoUrlWith:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoUrl;
}

- (UIView *)playVidewManagerGetPlayBackgroundViewWith:(NSIndexPath *)cellIndexPath
{
    LZVideoTableViewCell *cell = [self cellForRowAtIndexPath:cellIndexPath];
    
    return cell.playerBgView;
}

- (NSString *)playVideoManagerGetVideoIdWithIndexPath:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoId;
}

#pragma mark -
#pragma mark 控件初始化
- (LZCustomPlayerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LZCustomPlayerView alloc] init];
        _playerView.playCircle = YES;
    }
    
    return _playerView;
}

@end
